package com.tanhua.dubbo.server.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tanhua.dubbo.server.config.HuanXinConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TokenService {

    //环信redis缓存中的key值
    private static final String REDIS_KEY = "HX_TOKEN";

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 先从缓存中获取token
     * @return
     */
    public String getToken(){
        String token = this.redisTemplate.opsForValue().get(REDIS_KEY);
        if(StrUtil.isNotEmpty(token)){
            return token;
        }
        //缓存中取不到，调用环信的接口去获取token
        return this.refreshToken();
    }

    public String refreshToken(){
        //拼接环信的第三方api的url
        String targetUrl = this.huanXinConfig.getUrl()
                + this.huanXinConfig.getOrgName() + "/"
                + this.huanXinConfig.getAppName() + "/token";
        Map<String,String> map = new HashMap<>();
        //封装环信接口api需要的请求参数
        map.put("grant_type","client_credentials");
        map.put("client_id",this.huanXinConfig.getClientId());
        map.put("client_secret",this.huanXinConfig.getClientSecret());
        HttpResponse httpResponse = HttpRequest.post(targetUrl)
                .body(JSONUtil.toJsonStr(map))
                .timeout(20000) //超时时间(单位：毫秒)
                .execute();

        if(!httpResponse.isOk()){
            log.error("获取token失败");
            return null;
        }

        String body = httpResponse.body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        String token = jsonObject.getStr("access_token");
        //redis缓存中的token比环信的token提前1小时失效
        long timeOut = jsonObject.getLong("expires_in") - 3600;
        if(StrUtil.isNotEmpty(body)){
            //body不为空，说明已经获取到环信的token了
            //将其存入redis中，方便下一次获取
            this.redisTemplate.opsForValue().set(REDIS_KEY,token,timeOut,TimeUnit.SECONDS);
            return token;
        }
        return null;
    }


}
